﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using BLL.Workflows;
using DO.Workflows;

namespace BLL.Workers
{
    public class Register
    {
        public static Dictionary<string,Type> Components { get; set; }
        public static Dictionary<string, IWorker> Workers { get; set; }

        static Register()
        {
            Components=new Dictionary<string, Type>();
            Workers = new Dictionary<string, IWorker>();

            string dllFilePath = typeof(WorkflowComponentBase).Assembly.Location;
            DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(dllFilePath));
            while (dir.Name.ToLower() != "assembly" && dir.Parent != null)
            {
                dir = dir.Parent;
            }
            if (dir.Name.ToLower() == "assembly")
            {
                FileInfo[] dllInfos = dir.GetFiles("*.dll", SearchOption.AllDirectories);
                foreach (FileInfo dllInfo in dllInfos)
                {
                    try
                    {
                        Assembly assembly = Assembly.LoadFile(dllInfo.FullName);
                        Type[] types = assembly.GetTypes();
                        foreach (Type type in types)
                        {
                            if (type.IsSubclassOf(typeof(WorkflowComponentBase)) && !type.IsAbstract)
                                Components.Add(type.Name, type);
                            if(type.GetInterface(typeof(IWorker).FullName)!=null && !type.IsAbstract)
                            {
                                IWorker worker = (IWorker) Activator.CreateInstance(type);
                                Workers.Add(type.Name, worker);
                            }
                        }
                    }
                    catch
                    {
                    }
                }
            }
        }
    }
}
